mod css;
mod dom;
mod html;
mod layout;
mod painting;
mod style;

use std::default::Default;

pub fn write_image(html: String, css: String, image_path: &str) {
  let mut viewport: layout::Dimensions = Default::default();
  viewport.content.width = 800.0;
  viewport.content.height = 600.0;

  let root_node = html::parse(html);
  let stylesheet = css::parse(css);
  let style_root = style::style_tree(&root_node, &stylesheet);
  let layout_root = layout::layout_tree(&style_root, viewport);

  let canvas = painting::paint(&layout_root, viewport.content);
  let (w, h) = (canvas.width as u32, canvas.height as u32);
  let img = image::ImageBuffer::from_fn(w, h, move |x, y| {
    let color = canvas.pixels[(y * w + x) as usize];
    image::Pixel::from_channels(color.r, color.g, color.b, color.a)
  });
  let ok = image::DynamicImage::ImageRgba8(img)
    .save(image_path)
    .is_ok();

  if ok {
    println!("Save image to {}", image_path);
  } else {
    println!("Save image {} failed", image_path);
  }
}
